'use strict';
define(['../main','iCheck'],function(module){
    module.controller("settleCtrl",function($scope,$http,$rootScope){
        $rootScope.navActive='/web/settle';
        $scope.startTime= addDate(-1);          //开始时间
        $scope.endTime=addDate(-1);            //结束时间
        $scope.searchKey='';                    //查询关键字
        $scope.batchEnable=false;              //是否可进行批量操作
        $scope.checkAllStatus=false;           //全选按钮默认状态
        $scope.settleStatus=[];                 //结算状态列表
        $scope.currentSettleStatus;             //当前结算状态
        $scope.settleList=[];                   //结算数据集
        $scope.loadingBar={                     //进度条操作对象
            url:'',                  //请求链接
            defaultSendCount:10,      //默认每次发送数据条数
            currentCount:0,          //当前已发送数据条数
            totalCount:0,            //总条数
            inProcess:false,        //当前是否正在执行
            breaking:false,         //终止标示
            config:function(config){
                this.reset();
                if(config.url)this.url=config.url;
                if(config.totalCount&&config.totalCount>0) this.totalCount=config.totalCount;
                if(config.funGetParam)this._funGetParam=config.funGetParam;
                if(config.processCallback)this._processCallback=config.processCallback;
                if(config.endCallback)this._endCallback=config.endCallback;
                if(config.errorCallback)this._errorCallback=config.errorCallback;
                return this;
            },
            reset:function(){
                this.currentCount=0;
                this.inProcess=false;
                this.breaking=false;
            },
            start:function(){
                this.inProcess=true;
                var params=this._funGetParam(this.currentCount,this.defaultSendCount);
                var loadingBar=this;
                $http.get(this.url,{params:params}).success(function(data){
                    if(loadingBar.breaking){
                        loadingBar.breaking=false;
                        loadingBar.reset();
                        return null;
                    }
                    else{
                        loadingBar.currentCount+=loadingBar.defaultSendCount;
                        loadingBar._processCallback(data);
                        if(loadingBar.currentCount>=loadingBar.totalCount){
                            loadingBar.currentCount=loadingBar.totalCount;
                            loadingBar.inProcess=false;
                            loadingBar._endCallback();
                        }
                        else{
                            loadingBar.start();
                        }
                    }
                }).error(function(err){
                    loadingBar._errorCallback(err);
                });
            },
            stop:function(){
                this.breaking=true;
            },
            _funGetParam:function(currentIndex){

            },
            _processCallback:function(data){
                console.log(data);
            },
            _endCallback:function(){
                console.log("完成");
            },
            _errorCallback:function(err){
                alert(JSON.stringify(err));
            }
        };
        /**
         * 移除已完成操作的数据
         * @param list      操作的数据所对应id数组
         * @param property  该id数组对应的属性
         */
        var removeSettleData= function(list,property ){
            var tempList=[];
            for(var i=0;i<$scope.settleList.length;i++){
                var del=false;
                for(var j=0;j<list.length;j++){
                    if($scope.settleList[i][property]==list[j]){
                        del=true;
                        break;
                    }
                }
                if(!del) tempList.push($scope.settleList[i]);
            }
            $scope.settleList=tempList;
        };
        /**
         * 转存
         */
        var preDepositSettle=function(){
            var settleIds=[];
            for(var i=0;i<$scope.settleList.length;i++){
                if($scope.settleList[i].checked) settleIds.push($scope.settleList[i].settlementId);
            }
            console.log(settleIds);
            $http.get("api/settle/preDepositSettle",{params:{settlementIds:settleIds.join(",")}}).success(function(data){
                removeSettleData(settleIds,'settlementId');
            });
        };
        /**
         * 修改状态通用方法
         * @param newStatus
         */
        var changeStatus=function(newStatus){
            var settleIds=[];
            for(var i=0;i<$scope.settleList.length;i++){
                if($scope.settleList[i].checked) settleIds.push($scope.settleList[i].settlementId);
            }
            if(settleIds.length==0){
                alert("请选择至少一条数据");
                return;
            }
            $scope.loadingBar.config({
                url:"api/settle/updateSettleStatus",
                totalCount:settleIds.length,
                funGetParam:function(currentIndex,processCount){
                    var end=currentIndex+processCount;
                    var tempIds=[];
                    if(end<settleIds.length){
                        tempIds=settleIds.slice(currentIndex,end);
                    }
                    else{
                        tempIds=settleIds.slice(currentIndex);
                    }
                    console.log(tempIds);
                    return {settlementIds:tempIds.join(","),newStatus:newStatus};
                },
                processCallback:function(data,currentIndex,processCount){
                    var end=currentIndex+processCount;
                    var tempIds=[];
                    if(end<settleIds.length){
                        tempIds=settleIds.slice(currentIndex,end);
                    }
                    else{
                        tempIds=settleIds.slice(currentIndex);
                    }
                    removeSettleData(tempIds,'settlementId');
                }
            }).start();
        };
        /**
         * 修改状态-确认
         */
        var changeConfirm=function(){
            changeStatus(3);
        };
        /**
         * 修改状态-审核
         */
        var changeReview=function(){
            changeStatus(4);
        };
        /**
         * 修改状态-付款
         */
        var changePayed=function(){
            changeStatus(5);
        };
        function addDate(dadd,dd){
            var a = dd?new Date(dd):new Date();
            a = a.valueOf();
            a = a + dadd * 24 * 60 * 60 * 1000;
            a = new Date(a);
            var year=a.getFullYear();
            var month=a.getMonth()<9?'0'+(a.getMonth()+1):a.getMonth()+1;
            var date= a.getDate()<10?'0'+ a.getDate(): a.getDate();
            return year+"-"+ month+"-"+ date;
        }

        /**
         * 生成结算单
         * @param shopId    场馆Id，所有场馆传-1，部分勾选传空
         */
        var generateSettleList=function(shopId){
            var shopIds=[];
            if(shopId!=null){
                shopIds.push(shopId);
            }
            else{
                for(var i=0;i<$scope.settleList.length;i++){
                    if($scope.settleList[i].checked) shopIds.push($scope.settleList[i].shopId);
                }
            }
            $scope.loadingBar.config({
                url:"api/settle/createSettlement",
                totalCount:shopIds.length,
                funGetParam:function(currentIndex,processCount){
                    var end=currentIndex+processCount;
                    var tempShopIds=[];
                    if(end<shopIds.length){
                        tempShopIds=shopIds.slice(currentIndex,end);
                    }
                    else{
                        tempShopIds=shopIds.slice(currentIndex);
                    }
                    console.log(tempShopIds);
                    return {startTime:$scope.startTime,endTime:$scope.endTime,shopIds:tempShopIds.join(",")};
                },
                processCallback:function(data,currentIndex,processCount){
                    var end=currentIndex+processCount;
                    var tempShopIds=[];
                    if(end<shopIds.length){
                        tempShopIds=shopIds.slice(currentIndex,end);
                    }
                    else{
                        tempShopIds=shopIds.slice(currentIndex);
                    }
                    removeSettleData(tempShopIds,'shopId');
                }
            }).start();
        };
        $scope.settleGroup={                    //结算操作权限
            operationAndEvent:[
                {opName:'生成',event:generateSettleList},
                {opName:'确认',event:changeConfirm},
                {opName:'审核',event:changeReview},
                {opName:'转存',event:preDepositSettle},
                {opName:'付款',event:changePayed}
            ],
            settleStatusList:[
                {key:1,value:'未结算',opt:[0]},
                {key:2,value:'已生成',opt:[1]},
                {key:3,value:'已确认',opt:[2]},
                {key:4,value:'已审核',opt:[3]},
                {key:6,value:'已转存',opt:[4]},
                {key:5,value:'已付款',opt:[]}
            ],
            canOp:function(index){
                for(var i=0;i<this.currentSettleStatus.opt.length;i++){
                    if(this.currentSettleStatus.opt[i]==index){
                        return false;
                    }
                }
                return true;
            },
            currentSettleStatus:{}
        };


        /**
         * 加载结算数据集
         */
        $scope.loadResult=function(){
            $scope.settleList=[];
            var params={startTime:$scope.startTime,endTime:$scope.endTime,keyWord:$scope.searchKey};
            if($scope.settleGroup.currentSettleStatus.key==1){
                $http.get("api/settle/findSettleData",{params:params}).success(function(data){
                    $scope.settleList=data;
                    for(var i=0;i<$scope.settleList.length;i++){
                        $scope.settleList[i].checked=false;
                    }
                });
            }
            else{
                params.settleStatus=$scope.settleGroup.currentSettleStatus.key;
                $http.get("api/settle/findSettleDoc",{params:params}).success(function(data){
                    $scope.settleList=data;
                    for(var i=0;i<$scope.settleList.length;i++){
                        $scope.settleList[i].checked=false;
                    }
                });
            }
        };
        /**
         * 全选
         */
        $scope.checkAll=function(){
            $scope.checkAllStatus=!$scope.checkAllStatus;
            for(var i=0;i<$scope.settleList.length;i++){
                $scope.settleList[i].checked=$scope.checkAllStatus;
            }
            $scope.batchEnable=$scope.checkAllStatus;
        };
        /**
         * 点击数据行选中事件
         * @param index 下标
         */
        $scope.doCheck=function(index){
            $scope.settleList[index].checked = !$scope.settleList[index].checked;
            var checkCount=0;
            for(var i=0;i<$scope.settleList.length;i++){
                if($scope.settleList[i].checked){
                    checkCount++;
                }
            }
            if(checkCount==0){
                $scope.checkAllStatus=false;
                $scope.batchEnable=false;
            }
            else{
                $scope.batchEnable=true;
                $scope.checkAllStatus=(checkCount==$scope.settleList.length);
            }
        };
        $scope.exportResult=function(){
            $("#exportForm").submit();
        };
        /**
         * 初始化方法
         */
        function init(){
            $('.form_date').datetimepicker({
                format: 'yyyy-mm-dd',
                language:  'zh-CN',
                weekStart: 1,
                todayBtn:  1,
                autoclose: 1,
                todayHighlight: 1,
                startView: 2,
                minView: 2,
                forceParse: 0
            });
            $scope.settleGroup.currentSettleStatus=$scope.settleGroup.settleStatusList[0];
        }
        init();
    });
});
